package dk.kapetanovic.jaft;


import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;

import dk.kapetanovic.jaft.exception.InconsistentStateException;
import dk.kapetanovic.jaft.exception.TransactionException;
import dk.kapetanovic.jaft.transaction.Transaction;
import dk.kapetanovic.jaft.transaction.TransactionHandler;
import dk.kapetanovic.jaft.transaction.TransactionManager;
import dk.kapetanovic.jaft.transaction.TransactionManagerImpl;

public class MainTest {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		File journal = new File("playground\\files\\");
		File backup = new File("playground\\backup");
		
		if(false) {
			try {
				TransactionManager tm = TransactionManagerImpl.
					getRecoveryInstance(backup, journal);
				//TransactionHandler transaction = new 
				//	TransactionHandler(tm.beginTransaction());
				Transaction transaction = tm.beginTransaction();
				if(transaction == null) {
					System.out.println("Nothing to recover.");
					return;
				}
				
				transaction.rollback();
				
				System.out.println("errors=" + transaction.checkError());
				
				return;
			}
			catch (TransactionException e) {
				e.printStackTrace();
			} 
			catch (InconsistentStateException e) {
				e.printStackTrace();
			}
			
			return;
		}
		
		TransactionManager tm = TransactionManagerImpl.
			getOutputInstance(backup, journal);
		
		System.out.println("Backup dir=" + tm.getBackupDir().getAbsolutePath());
		System.out.println("Journal dir=" + journal.getAbsolutePath());
		
		try {
			TransactionHandler transaction = new TransactionHandler(
				tm.beginTransaction());
			
			transaction.rename("playground\\user.png", 
				"playground\\files\\user.png1.dat");
			BufferedWriter wrt = new BufferedWriter(transaction.
				openFileWriter("playground\\text_wrt.txt", false));
			
			String abc = "abcdefghijklmnopqrstuvwxyz";
			wrt.write("alfabet = " + abc + "\n");
			for(int i = 0; i < abc.length(); i++)
				wrt.write(i + " " + abc.charAt(i) + "\n");
			wrt.close();
			
			transaction.delete("playground\\transaction.dat");
			transaction.rename("playground\\text_wrt.txt", "playground\\finish.txt");
			//transaction.delete("playground\\files\\");
			
			System.out.println("Rollback --");
			
			transaction.rollback();
			System.out.println("Finished without exceptions");
		} 
		catch (InconsistentStateException e) {
			System.out.println("Iconsisten error");
			e.getCause().printStackTrace();
		} 
		catch (TransactionException e) {
			System.out.println("Transaction error");
			e.getCause().printStackTrace();
		} 
		catch (IOException e) {
			System.out.println("IOExcpetion error");
			e.printStackTrace();
		}
	}
}
